// pages/page/orderpage/orderpage.js
const app = getApp();
var request_api = require('../../../utils/require_api.js')
var time = require('../../../utils/timechange.js');
import Dialog from '../../../youzan/youzan_dist/dialog/dialog';
import Toast from '../../../youzan/youzan_dist/toast/toast';
Page({
  /**
   * 页面的初始数据
   */
  data: {
    address: {},
    money: 0,
    totalmoney: 0,
    targetTime: 0,
    clearTimer: false,
    orderotem: [],
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var that = this;
    var orderstatus1 = '';

    //获取balance
    request_api.request(
      'select_openiduser', //需要传给wxrequest.js 的 url
      {
        "openid": app.globalData.openid
      }, //需要传的 data
      function(res) {
        that.data.money = res.data.balance;
      },
      function() {
        console.log("錯誤");
      },
    )
    this.data.goodsid = options.order_item;
    request_api.request(
      'getaddress', //需要传给wxrequest.js 的 url
      {
        "orderid": this.data.goodsid
      }, //需要传的 data
      function (res) {
        that.setData({
          address: res.data,
        })
        console.log(res, "that.data.money百度啊");
      },
      function () {
        console.log("錯誤");
      },
    )

    


    let addressdata = {};
    // wx.getStorage({
    //   key: 'address',
    //   success(res) {
    //     addressdata = res.data;
    //     that.setData({
    //       address: addressdata,
    //     })
    //   }
    // })
    //这里是获取到某条订单下面的款有哪些
    request_api.request(
      'getorderbyoid', {
        orderid: that.data.goodsid
      },
      function(res) {
        console.log(res, "nihao1");
        if (res.data[0].orderstatus == 0) {
          orderstatus1 = '未付款';
        } else if (res.data[0].orderstatus == 1) {
          orderstatus1 = '待发货';
        } else if (res.data[0].orderstatus == 2) {
          orderstatus1 = '已发货';
        } else if (res.data[0].orderstatus == 3) {
          orderstatus1 = '交易成功';
        } else if (res.data[0].orderstatus == 4) {
          orderstatus1 = '交易关闭';
        }
        that.setData({
          orders: res.data, //orders[0].totalmoney
          orderstatus: res.data[0].orderstatus,
          orderstatus1: orderstatus1,
          targetTime: res.data[0].create_time + 86400000,
          // targetTime: new Date().getTime() + 5000,
          timset: time.formatTime(res.data[0].create_time, 'Y/M/D h:m:s')
        })
        that.data.orderotem = res.data;
        that.data.totalmoney = res.data[0].totalmoney;
      },
      function() {
        console.log("錯誤");
      },
    )
  },

  /**
   * 计算总价
   */
  getTotalPrice(orders) {
    let total = 0;
    for (let i = 0; i < orders.length; i++) {
      total += orders[i].num * orders[i].price;
    }
    this.setData({
      total: this.numberFormat(total)
    })
  },

  //支付
  pay() {
    var that = this;
    if (that.data.money < that.data.totalmoney) {
      Dialog.alert({
        title: '余额不足',
        message: '您的余额不足，请前往充值页面进行充值！！'
      }).then(() => {
        wx.redirectTo({
          url: '../my_wallet/my_wallet',
        })
      });
      // 把订单变成为支付状态，，生成订单
      // 更改库存数量
      // 删除购物车表
    } else {

      //对于订单款号增加销量
      console.log(that.data.orderotem, "orders");
      let style_id='';
      let Quantity='';
      for (let i = 0; i < that.data.orderotem.length; i++) {
        style_id = style_id+ that.data.orderotem[i].goods_id+',';
        Quantity = Quantity+ that.data.orderotem[i].num+',';
      }
      //增加销量
      request_api.request(
        'update_xiaoliang', //需要传给wxrequest.js 的 url
        {
          "style_id": style_id,
          "Quantity": Quantity
        }, //需要传的 data
        function (res) {

        },
        function () {
          console.log("錯誤");
        },
      )
      //增加一条通知信息
      request_api.request(
        'insertannouncement', //需要传给wxrequest.js 的 url
        {
          "title": "订单支付成功通知",
          "content": "恭喜！您的订单已成功支付，详情请到我的订单查看！",
          "user_id": app.globalData.openid,
          "if_read": 0,
        }, //需要传的 data
        function (res) {
          console.log(res, "充值通知插入数据库成功，orderpage")
        },
        function () {
          console.log("錯誤");
        },
      )

      request_api.request( //成功支付减少用户金额
        'update_del_user', {
          "balance": that.data.totalmoney,
          "openid": app.globalData.openid
        }, //需要传的 data
        function(res) {
          //修改订单状态
          request_api.request(
            'update_orderstatus', //需要传给wxrequest.js 的 url
            {
              "orderId": that.data.goodsid,
              "orderstatus": '1'
            }, //需要传的 data
            function(res) {
              Toast.loading({
                duration: 2000, // 持续展示 toast
                forbidClick: true, // 禁用背景点击
                message: '加载中......',
                loadingType: 'spinner',
              });
              setTimeout(function() {
                Toast.success('成功付款！！！');
                that.update_status(); //更新界面状态
              }, 2500);
            },
            function() {
              console.log("錯誤");
            },
          )
        }
      )
      //更改库存表的数量





    }
  },



  update_status() {
    var that = this;
    var orderstatus1 = '';
    //这里是获取到某条订单下面的款有哪些
    request_api.request(
      'getorderbyoid', {
        orderid: that.data.goodsid
      },
      function(res) {
        console.log(res, "nihao");
        if (res.data[0].orderstatus == 0) {
          orderstatus1 = '未付款';
        } else if (res.data[0].orderstatus == 1) {
          orderstatus1 = '待发货';
        } else if (res.data[0].orderstatus == 2) {
          orderstatus1 = '已发货';
        } else if (res.data[0].orderstatus == 3) {
          orderstatus1 = '交易成功';
        } else if (res.data[0].orderstatus == 4) {
          orderstatus1 = '交易关闭';
        }
        that.setData({
          orders: res.data, //orders[0].totalmoney
          orderstatus: res.data[0].orderstatus,
          orderstatus1: orderstatus1,
          timset: time.formatTime(res.data[0].create_time, 'Y/M/D h:m:s')
        })

        that.data.totalmoney = res.data[0].totalmoney;
      },
      function() {
        console.log("錯誤");
      },
    )
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    this.setData({
      clearTimer: true
    });
  },

//取消订单
  cancal_order(){
    var that = this;
    let goodsid=[];
    let colorid=[];
    let filed=[];
    let num=[];
  for(let i=0;i<this.data.orderotem.length;i++){
    goodsid.push(this.data.orderotem[i].goods_id);
      colorid.push(this.data.orderotem[i].ColorID);
    filed.push(this.data.orderotem[i].Filed);
      num.push(this.data.orderotem[i].num);
  }
    request_api.request( //增加库存数量
      'update_f002quajia', {
        quatity: num,
        goodsid: goodsid,
        colorid: colorid,
        Filed: filed
      },
      function (res) {
        console.log(res, "我是增加的库存");
      },
      function () {
        console.log("錯誤");
      },
    )
    //修改结束时间
    var timestamp = Date.parse(new Date());
    var time = that.format_time(timestamp);
    request_api.request( //增加库存数量
      'update_closetime', {
        close_time: time,
        orderId: this.data.goodsid,
      },
      function (res) {
        console.log(res, "我是修改结束时间");
      },
      function () {
        console.log("錯誤");
      },
    )
    //更改状态为关闭订单
    //修改订单状态
    request_api.request(
      'update_orderstatus', //需要传给wxrequest.js 的 url
      {
        "orderId": this.data.goodsid,
        "orderstatus": '4'
      }, //需要传的 data
      function (res) {
        that.update_status(); //更新界面状态
      },
      function () {
        console.log("錯誤");
      },
    )
  },

  confirm_receipt(res){
    var that = this;
    var timestamp = Date.parse(new Date());
    var time = that.format_time(timestamp);
    var that = this;
    Toast.loading({
      duration: 2000, // 持续展示 toast
      forbidClick: true, // 禁用背景点击
      message: '加载中......',
      loadingType: 'spinner',
    });
    //修改订单状态
    request_api.request( 
      'update_closetime', {
        close_time: time,
        orderId: that.data.goodsid,
      },
      function (res) {
        console.log(res, "我是修改结束时间");
      },
      function () {
        console.log("錯誤");
      },
    )
    setTimeout(function () {
      request_api.request(
        'update_orderstatus', //需要传给wxrequest.js 的 url
        {
          "orderId": that.data.goodsid,
          "orderstatus": '3'
        }, //需要传的 data
        function (res) {
          Toast.success('收货成功！！！');
          that.update_status(); //更新界面状态
        },
        function () {
          console.log("錯誤");
        },
      )
    }, 2500);

  },


  //查看物流
  view_logistics1(option) {
    wx.navigateTo({
      url: '../view_logistics/view_logistics?orderid=' + this.data.orderotem[0].orderId,
    })
  },

  myLinsterner(e) {
    var that = this;
    //修改回库存数量
    let goods_ids = '';
    let num = '';
    for (let i = 0; i < that.data.orderotem.length; i++) {
      goods_ids += that.data.orderotem[i].goods_id + ',';
      num += that.data.orderotem[i].num + ',';
    }
    // request_api.request( //增加库存数量
    //   'update_f002quajia', {
    //     quatity: num,
    //     goodsid: goods_ids
    //   },
    //   function(res) {
    //     console.log(res, "我是增加的库存");
    //   },
    //   function() {
    //     console.log("錯誤");
    //   },
    // )
    //更改状态为关闭订单
    //修改订单状态
    // request_api.request(
    //   'update_orderstatus', //需要传给wxrequest.js 的 url
    //   {
    //     "orderId": that.data.goodsid,
    //     "orderstatus": '4'
    //   }, //需要传的 data
    //   function(res) {
    //     that.update_status(); //更新界面状态
    //   },
    //   function() {
    //     console.log("錯誤");
    //   },
    // )
  },
//查看物流
  view_logistics(){

  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },
  format_time(time) {
    var date = new Date(time);
    let Y = date.getFullYear() + '-';
    let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
    let D = date.getDate() + ' ';
    let h = date.getHours() + ':';
    let m = date.getMinutes() + ':';
    let s = date.getSeconds();
    return Y + M + D + h + m + s;
    console.log(Y + M + D + h + m + s);
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})